package com.ruoyi.xsp.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.constant.RedisConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.SendMsgType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.redis.RedisCacheUtil;
import com.ruoyi.xsp.domain.XspUserAuth;
import com.ruoyi.xsp.domain.XspUserLoginLog;
import com.ruoyi.xsp.domain.api.LoginUser;
import com.ruoyi.xsp.service.IXspUserAuthService;
import com.ruoyi.xsp.service.IXspUserLoginLogService;
import com.ruoyi.xsp.service.IXspUserRegCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.xsp.mapper.XspUserMapper;
import com.ruoyi.xsp.domain.XspUser;
import com.ruoyi.xsp.service.IXspUserService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户管理Service业务层处理
 *
 * @author zhiminhu
 * @date 2021-01-22
 */
@Service
public class XspUserServiceImpl implements IXspUserService {
    @Autowired
    private XspUserMapper xspUserMapper;

    @Autowired
    private IXspUserLoginLogService xspUserLoginLogService;
    @Autowired
    private IXspUserRegCodeService xspUserRegCodeService;
    @Autowired
    private IXspUserAuthService xspUserAuthService;

    @Autowired
    private RedisCacheUtil redisCache;

    /**
     * 查询用户管理
     *
     * @param userId 用户管理ID
     * @return 用户管理
     */
    @Override
    public XspUser selectXspUserById(Long userId) {
        return xspUserMapper.selectXspUserById(userId);
    }

    @Override
    public XspUser selectXspUserByUserCode(Long userCode ) {
        return xspUserMapper.selectXspUserByUserCode(userCode);
    }

    @Override
    public XspUser selectXspUserForCacheByUserCode(Long userCode) {
        XspUser xspUser = xspUserMapper.selectXspUserByUserCode(userCode);
        XspUser xspUserCount= xspUserMapper.selectXspUserSumByUserCode(userCode);
        xspUser.setFansCount(xspUserCount.getFansCount());
        xspUser.setLikeCount(xspUserCount.getLikeCount());
        xspUser.setConcernedCount(xspUserCount.getConcernedCount());
        xspUser.setNewsCount(xspUserCount.getNewsCount());
        xspUser.setLikeNewsCount(xspUserCount.getLikeNewsCount());
        redisCache.setCacheObject(RedisConstants.USER_INFO_PREFIX + userCode, xspUser);
        return xspUser;
    }

    /**
     * 获取用户相关的几个统计数据
     * 作品数量，喜欢作品数量，关注用户数等等
     * @param userCode
     * @return
     */
    @Override
    public XspUser selectXspUserSumByUserCode(Long userCode){
       return xspUserMapper.selectXspUserSumByUserCode(userCode);
    }
    /**
     * 登陆
     *
     * @param user
     * @return
     */
    @Transactional
    @Override
    public AjaxResult login(HttpServletRequest request, LoginUser user) {
        final String ip = ShiroUtils.getIp();
        XspUser xspUser;
        switch (user.getSource()) {
            case "sj":
                //region 手机号码方式注册...
                String phoneNumber = user.getPhonenumber();
                String password = user.getPassword();
                if (StringUtils.isBlank(phoneNumber)) {
                    return AjaxResult.error("手机号码不能为空");
                }
                if (!StringUtils.isBlank(user.getCaptcha())) {
                    //验证码登陆
                    String msgKey = RedisConstants.MESSAGE_CODE_PREFIX + SendMsgType.OK.getCode() + "-" + user.getPhonenumber();
                    String msgCode = redisCache.getCacheObject(msgKey);

                    if (msgCode == null) {
                        return AjaxResult.error("验证码已失效");
                    }
                    if (msgCode.equals(user.getCaptcha())) {
                        redisCache.deleteObject(msgKey);
                        HashMap<String, String> map = new HashMap<>();
                        map.put("phonenumber", phoneNumber);
                        xspUser = xspUserMapper.loginByphoneNumber(map);
                    } else {
                        return AjaxResult.error("验证码错误");
                    }
                } else {
                    //密码登陆
                    if (StringUtils.isBlank(password)) {
                        return AjaxResult.error("密码不能为空");
                    }
                    HashMap<String, String> map = new HashMap<>();
                    map.put("phonenumber", phoneNumber);
                    map.put("password", password);
                    xspUser = xspUserMapper.loginByphoneNumber(map);
                    if (xspUser == null) {
                        return AjaxResult.error("账号或者密码不匹配");
                    }
                }
                // 创建用户
                if (xspUser == null) {
                    xspUser = createUser(user);
                    xspUser.setNewUser(true);
                } else {
                    xspUser.setNewUser(false);
                }
                break;

            case "wx":
            case "qq":
            case "pg": //苹果三方登录
                if (StringUtils.isBlank(user.getOpenId())) {
                    return AjaxResult.error("OpenId不能为空");
                }
                XspUserAuth param = new XspUserAuth();
                param.setOpenId(user.getOpenId());
                param.setSource(user.getSource());
                List<XspUserAuth> auths = xspUserAuthService.selectXspUserAuthList(param);
                if (auths == null || auths.size() == 0) {
                    xspUser = createUser(user);
                    createUserAuth(xspUser, user);
                    xspUser.setNewUser(true);
                } else {
                    xspUser = xspUserMapper.selectXspUserByUserCode(auths.get(0).getUserCode());
                    xspUser.setNewUser(false);
                }
                break;
            default:
                throw new IllegalStateException("用户来源未知无法注册 Unexpected value: " + user.getSource());
        }
        String token = Md5Utils.hash(request.getSession().getId() + System.currentTimeMillis() + xspUser.getUserCode());
        xspUser.setToken(token);
        //汇总信息
         XspUser xspUserSum=  xspUserMapper.selectXspUserSumByUserCode(xspUser.getUserCode());
        xspUser.setFansCount(xspUserSum.getFansCount());
        xspUser.setLikeCount(xspUserSum.getLikeCount());
        xspUser.setConcernedCount(xspUserSum.getConcernedCount());
        xspUser.setNewsCount(xspUserSum.getNewsCount());
        xspUser.setLikeNewsCount(xspUserSum.getLikeNewsCount());
        //删除旧token
        String oldToken = redisCache.getCacheObject(RedisConstants.USER_TOKEN_PREFIX + xspUser.getUserCode());
        redisCache.deleteObject(RedisConstants.TOKEN_USER_PREFIX + oldToken);
        //设置新token
        redisCache.setCacheObject(RedisConstants.USER_INFO_PREFIX + xspUser.getUserCode(), xspUser, 8, TimeUnit.DAYS);
        redisCache.setCacheObject(RedisConstants.TOKEN_USER_PREFIX + token, xspUser.getUserCode(), 7, TimeUnit.DAYS);
        redisCache.setCacheObject(RedisConstants.USER_TOKEN_PREFIX + xspUser.getUserCode(), token, 7, TimeUnit.DAYS);


        XspUserLoginLog log = new XspUserLoginLog();
        log.setUserId(xspUser.getUserId());
        log.setUserCode(xspUser.getUserCode());
        log.setSocialUserId("");
        log.setSource(user.getSource());
        log.setPhoneModel(xspUser.getPhonenumber());
        log.setIpaddr(ip);
        log.setLoginLocation("");
        log.setBrowser("");
        log.setOs("");
        log.setActionType(0);
        log.setIsNewUser(xspUser.isNewUser() == true ? 1 : 0);
        log.setDeviceNum("");
        log.setCreateTime(new Date());
        log.setUpdateTime(new Date());

        xspUserLoginLogService.insertXspUserLoginLog(log);
        return AjaxResult.success(xspUser);
    }

    @Transactional
    public XspUser createUser(LoginUser user) {
        final String ip = ShiroUtils.getIp();
        XspUser xspUser = new XspUser();
        xspUser.setUserCode(xspUserRegCodeService.fetchUserCode().getUserCode());
        if (StringUtils.isBlank(user.getAvatar())) {
            xspUser.setAvatar("http://pic.e-sports.cn/esport_match_1578900713352.png");
        } else {
            xspUser.setAvatar(user.getAvatar());
        }
        if (StringUtils.isBlank(user.getNickname())) {
            xspUser.setAvatar("pl" + xspUser.getUserCode());
        } else {
            xspUser.setAvatar(user.getNickname());
        }
        xspUser.setLoginName("" + xspUser.getUserCode());
        xspUser.setPhonenumber(user.getPhonenumber());
        xspUser.setPassword(user.getPassword());
        xspUser.setNickname(user.getNickname());
        xspUser.setStatus("0");
        xspUser.setBirthday(DateUtils.getNowDate());
        xspUser.setSex("0");
        xspUser.setUserType("0");
        xspUser.setLoginDate(new Date());
        xspUser.setCreateTime(new Date());
        xspUser.setDelFlag("0");
        xspUser.setSalt(ShiroUtils.randomSalt());
        xspUser.setLoginIp(ip);
        xspUserMapper.insertXspUser(xspUser);
        return xspUser;
    }

    public XspUserAuth createUserAuth(XspUser xspUser, LoginUser user) {
        XspUserAuth auth = new XspUserAuth();
        auth.setUserCode(xspUser.getUserCode());
        auth.setSource(user.getSource());
        auth.setOpenId(user.getOpenId());
        auth.setDelFlag("0");
        auth.setUserId(xspUser.getUserId());
        auth.setCreateTime(new Date());
        xspUserAuthService.insertXspUserAuth(auth);
        return auth;
    }

    /**
     * 查询用户管理列表
     *
     * @param xspUser 用户管理
     * @return 用户管理
     */
    @Override
    public List<XspUser> selectXspUserList(XspUser xspUser) {
        return xspUserMapper.selectXspUserList(xspUser);
    }

    @Override
    public List<XspUser> selectXspUserMyFriendList(XspUser xspUser) {
        return xspUserMapper.selectXspUserMyFriendList(xspUser);
    }

    @Override
    public List<XspUser> selectXspUserMyConcernedList(XspUser xspUser) {
        return xspUserMapper.selectXspUserMyConcernedList(xspUser);
    }

    @Override
    public List<XspUser> selectXspUsermyFansList(XspUser xspUser) {
        return xspUserMapper.selectXspUsermyFansList(xspUser);
    }

    /**
     * 新增用户管理
     *
     * @param xspUser 用户管理
     * @return 结果
     */
    @Override
    public int insertXspUser(XspUser xspUser) {
        xspUser.setCreateTime(DateUtils.getNowDate());
        return xspUserMapper.insertXspUser(xspUser);
    }

    /**
     * 修改用户管理
     *
     * @param xspUser 用户管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateXspUser(XspUser xspUser) {
        xspUser.setUpdateTime(DateUtils.getNowDate());
        int result = xspUserMapper.updateXspUser(xspUser);
        return result;
    }

    /**
     * 删除用户管理对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteXspUserByIds(String ids) {
        return xspUserMapper.deleteXspUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除用户管理信息
     *
     * @param userId 用户管理ID
     * @return 结果
     */
    @Override
    public int deleteXspUserById(Long userId) {
        return xspUserMapper.deleteXspUserById(userId);
    }
}
